
#include<sys/socket.h>
#include<sys/un.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<stdio.h>
#include <string.h>
#include "dbm_conf.h"
#include <fcntl.h>
#include "server/dbm_socket.h"
int dbm_connect(){
	int ret;
	struct sockaddr_un bmserver_addr; //unix socket
	ret = socket(AF_LOCAL,SOCK_STREAM,0); //type AF_LOCAL
	if(ret < 0)
	{
		//printf("can't create socket\n");
		DEBUG(INFO,"can't create socket");
		return -1;
	}
	bzero(&bmserver_addr,sizeof(bmserver_addr));
	bmserver_addr.sun_family = AF_LOCAL;
	strcpy(bmserver_addr.sun_path,UNIXSTR_PATH);

	if(connect(ret,(struct sockaddr*)&bmserver_addr,sizeof(bmserver_addr))<0)
	{
		//printf("connect error\n");
		DEBUG(INFO,"connect error");
		return -1;
	}
	DEBUG(INFO,"successfully connected!");
//	printf("dbm_socket:successful connected!\n");
	global_bm_sock = ret;
	return 0;
}


int dbm_send_packet(struct packet* pkt){
	//DEBUG(INFO, "%s %d %d %u send_packet handle",pkt->ip, pkt->sockfd, pkt->ops_type, pkt->len);
		int ret;

		ret = send(pkt->sockfd, pkt->head, pkt->len,0);
		if (ret == -1) {
			DEBUG(ERROR, "send_packet send failed :type:[%d] --%s",pkt->type, strerror(errno));
			return -1;
		}
		DEBUG(INFO, "%d %d %u %u send_packet send", pkt->sockfd,pkt->type, pkt->len, ret);

		return ret;
}
struct packet* dbm_recv_packet(){
	int ret;
	struct packet* pkt;
	Packet_header header;
	//int flags= fcntl(global_bm_sock,F_GETFL,0);
	//fcntl(global_bm_sock,F_SETFL,flags|O_NONBLOCK);
	ret = recv(global_bm_sock,&header,8,0); //recv the packet's header
	if(ret<0)return NULL;
	//DEBUG(INFO,"%d %d %d %d\n",header.action,header.dest_module,header.length,header.sour_module);
	int packet_len = header.length;
	if(header.dest_module!=DBM){
		//DEBUG(INFO,"WRONG PACKET!\n");
		return NULL;
	}
	//u_char* pkt_data = (u_char*)malloc(packet_len);
	pkt = (struct packet*)malloc(sizeof(struct packet));
	pkt->head = (u_char*)malloc(packet_len+8);
	memcpy(pkt->head,&header,8);
	pkt->sockfd = global_bm_sock;
	pkt->len = packet_len + sizeof(Packet_header);
	pkt->body = pkt->head+8;
	ret = recv(global_bm_sock,(void*)(pkt->head+8),packet_len,0);
//	DEBUG(INFO,"%s",strerror(errno));
	//DEBUG(INFO,"Packet Body:: %s",pkt->body);
	if(ret<0)return NULL;
	return pkt;

}
void str_cli(FILE* fp,int sockfd){
	char sendline[100],recvline[100];
	while(fgets(sendline,100,fp)!= NULL){
		write(sockfd,sendline,strlen(sendline));
		if(read(sockfd,recvline,100)==0)
			printf("str_cli:server terminated prematurely");
		fputs(recvline,stdout);
	}
}
